//
//  CustomTableViewCell.m
//  Vedio
//
//  Created by Hu Jianguo on 13-4-4.
//  Copyright (c) 2013年 Shida. All rights reserved.
//

#import "CustomTableViewCell.h"
#import "ProfessionalViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreMedia/CoreMedia.h>
//#import <AVAsset.h>
@implementation CustomTableViewCell
//@synthesize btnPlay,btnDownload;
@synthesize lbComment,lbdate,lbtitle;
@synthesize vidioDate,vedioDesc,vediotitle,vediosource;

@synthesize moviePrview;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        //CGSize viewSize = self.frame.size;
        
        //UIImage* moveImag = [[UIImage alloc] initWithContentsOfFile:movieURL];
        UIImage* moveImag = [self GetVedioImage];
        UIImageView* moveImageView = [[UIImageView alloc] initWithImage:moveImag];
        //moveImageView.backgroundColor = [UIColor redColor];
        moveImageView.frame = CGRectMake(10, 10, 100, 90);
        [self addSubview:moveImageView];
        //[moveImag release];
        

        self.lbComment = [[UILabel alloc] initWithFrame:CGRectMake(140, 20, 300, 50)];
        self.lbComment.backgroundColor = [UIColor clearColor];
        UIFont* font = [UIFont systemFontOfSize:14];
        [self.lbComment setFont:font];
        [self addSubview:self.lbComment];

        lbtitle = [[UILabel alloc] initWithFrame:CGRectMake(140, 1, 300, 50)];
      
        lbtitle.backgroundColor = [UIColor clearColor];
        font = [UIFont systemFontOfSize:14];
        [self.lbtitle setFont:font];
        [self addSubview:lbtitle];
        
        lbdate = [[UILabel alloc] initWithFrame:CGRectMake(200, 20, 300, 50)];
        lbdate.backgroundColor = [UIColor clearColor];
        font = [UIFont systemFontOfSize:14];
        [self.lbdate setFont:font];
        
        [self addSubview:lbdate];
        
    
        
        UIButton* btnPlay = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnPlay setBackgroundImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        [btnPlay setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateHighlighted]; 
        btnPlay.frame = CGRectMake(140, 60, 45, 30);
        //[btnPlay setTitle:@"Play" forState:UIControlStateNormal];
        [btnPlay.titleLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
        [btnPlay addTarget:self action:@selector(moviePlay:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btnPlay];
        
        
        UIButton* btnDownload = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnDownload setBackgroundImage:[UIImage imageNamed:@"download.png"] forState:UIControlStateNormal];
        [btnDownload setImage:[UIImage imageNamed:@"download.png"] forState:UIControlStateHighlighted];
        //[btnDownload setTitle:@"Download" forState:UIControlStateNormal];
        [btnDownload.titleLabel setFont:[UIFont fontWithName:@"Arial" size:14]];
        
        btnDownload.frame = CGRectMake(200, 60, 30 , 30);
        [btnDownload addTarget:self action:@selector(movieDownload:) forControlEvents:UIControlEventTouchUpInside];
        //[self addSubview:btnDownload];

            
    }
    return self;
}

-(UIImage*)GetVedioImage
{
    if(self.vediosource == nil)
    {
        return nil;
    }
    
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO]   forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    
    NSArray* addrs = [self.vediosource componentsSeparatedByString:@" "];
    NSString* strurl = [NSString stringWithFormat:@"%@",addrs[0]];
    //NSURL *url = [[NSURL alloc] initFileURLWithPath:strurl];
    NSURL* url = [NSURL URLWithString:strurl];

    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    
   // int seconds = urlAsset.duration.value/urlAsset.duration.timescale;
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(600, 450);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(10, 10) actualTime:NULL error:&error];
    UIImage *image = [UIImage imageWithCGImage: img];

    return image;
}

#pragma - update vedio comment and preview
-(void)updateCommentAndPreview
{
    self.lbComment.text = movieComment;
    self.lbtitle.text = self.vediotitle;
    
    NSArray* arrays = [self.vidioDate componentsSeparatedByString:@" "];
    self.lbdate.text = arrays[0];
    
    UIImage* moveImag = [self GetVedioImage];
    UIImageView* moveImageView = [[UIImageView alloc] initWithImage:moveImag];
    //moveImageView.backgroundColor = [UIColor redColor];
    moveImageView.frame = CGRectMake(10, 10, 100, 90);
    [self addSubview:moveImageView];
}

#pragma - play and download function
-(void)moviePlay:(id)send
{
    [myprofessional readyPlay:self.vediosource];
    //[self readyPlay];
}

-(void)movieDownload:(id)send
{
    
    
}

//-(void)readyPlay
//{
//    moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:VEDIO_RUL]];
//    
//    if ([moviePlayer respondsToSelector:@selector(loadState:)])
//    {
//        
//        [moviePlayer setControlStyle:MPMovieControlStyleFullscreen];        //
//        //满屏
//        [moviePlayer setFullscreen:YES];
//        // 有助于减少延迟
//        [moviePlayer prepareToPlay];
//        
//        
//        [[NSNotificationCenter defaultCenter] addObserver:self
//                                                 selector:@selector(moviePlayerLoadStateChanged:)
//                                                     name:MPMoviePlayerLoadStateDidChangeNotification
//                                                   object:nil];
//    }
//    else
//    {
//        [self addSubview:[moviePlayer view]];
//
//        [moviePlayer play];
//    }
//    
//    //播放结束
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(moviePlayerBackDidFinish:)
//                                                 name:MPMoviePlayerPlaybackDidFinishNotification
//                                               object:nil];
//    
//}
//
//
//#pragma - movie play
//-(void)moviePlayerLoadStateChanged:(NSNotification*)notification
//{
//    if ([moviePlayer loadState] == MPMovieLoadStateUnknown)
//    {
//        
//        [[NSNotificationCenter     defaultCenter] removeObserver:self
//                                                            name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
//        [self addSubview:[moviePlayer view]];
//    }
//    
//}
//
//-(void)moviePlayerBackDidFinish:(NSNotification*)notification
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
//}

-(void)setParentViewController:(ProfessionalViewController*)pro
{
    myprofessional = pro;
}
    
#pragma -
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

#pragma - 外面赋值接口
-(void)setMovieURL:(NSString*)MovieURL
{
    movieURL = MovieURL;
}

-(void)setMovieComment:(NSString*)MovieComment;
{
    movieComment = MovieComment;
}

-(void)setCellIndex:(NSInteger)cIndex
{
    cellIndex = cIndex;
}
#pragma - movie download

//-(void)startDownload
//{
//    ASIHTTPRequest* downloadRequest = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:self.vediosource]];
//    downloadRequest.delegate = self;
//    NSString* path = downloadPath;
//    NSString *savePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"p_%d.mp4",cellIndex]];
//	//初始化临时文件路径
//	NSString *tempPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"temp/book_%d.mp4.temp",cellIndex]];
//	//设置文件保存路径
//	[downloadRequest setDownloadDestinationPath:savePath];
//	//设置临时文件路径
//	[downloadRequest setTemporaryFileDownloadPath:tempPath];
//    
//    //设置进度条的代理,
//	[downloadRequest setDownloadProgressDelegate:self];
//	//设置是是否支持断点下载
//	[downloadRequest setAllowResumeForFileDownloads:YES];
//    
//    [downloadRequest setUserInfo:@{@"redio": @(cellIndex)}];
//    
//    [networkQueue addOperation:downloadRequest];
//    [downloadRequest release];
//    
//}
//
//-(void)pauseDownload
//{
//    for (ASIHTTPRequest* request in [networkQueue operations])
//    {
//        NSInteger cellid = [(request.userInfo)[@"redio"] intValue];
//        if (cellid == cellIndex)
//        {
//            [request clearDelegatesAndCancel];
//            break;
//        }
//    }
//}

-(void)continueDownload
{
    
}


#pragma - 
//-(void)setNetworkQueue:(ASINetworkQueue*)queue
//{
//    networkQueue = queue;
//}

#pragma -

-(void)setDownloadPath:(NSString*)path
{
    downloadPath = path;
}

#pragma - asihttp delegate

//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{
//	NSLog(@"didReceiveResponseHeaders-%@",[responseHeaders valueForKey:@"Content-Length"]);
//    
//    NSLog(@"contentlength=%f",request.contentLength/1024.0/1024.0);
//    int bookid = [(request.userInfo)[@"bookID"] intValue];
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    float tempConLen = [[userDefaults objectForKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]] floatValue];
//    NSLog(@"tempConLen=%f",tempConLen);
//    //如果没有保存,则持久化他的内容大小
//    if (tempConLen == 0 )
//    {   //如果没有保存,则持久化他的内容大小
//        [userDefaults setObject:[NSNumber numberWithFloat:request.contentLength/1024.0/1024.0] forKey:[NSString stringWithFormat:@"book_%d_contentLength",bookid]];
//    }
//    
//}
////ASIHTTPRequestDelegate,下载完成时,执行的方法
//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    
//    //int cellid = [[request.userInfo objectForKey:@"redio"] intValue];
//
//    //cell.downloadCompleteStatus = YES;
//    //cell.progressView.progress = 0.0;
//}
@end
